import java.util.LinkedList;
import java.util.Queue;

//飞地的数量
//测试链接：https://leetcode.cn/problems/number-of-enclaves/
public class NumEnclaves {
    /**
     从四周的1出发去搜索看能搜索到多少1
     */
    int[] dx = {-1,1,0,0};
    int[] dy = {0,0,-1,1};
    int m,n;
    public int numEnclaves(int[][] grid) {
        m = grid.length; n = grid[0].length;
        boolean[][] vis = new boolean[m][n];

        int total = 0;  //总共多少个陆地
        int enable = 0; //能够到达边界的陆地

        Queue<int[]> q = new LinkedList<>();
        //将四周都为1的添加进队列
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    total++;  //记录一共有多少陆地
                }
                //四周的位置
                if( (i == 0 || j==0 || j== n-1 || i ==m-1 ) && grid[i][j] == 1) {
                    q.add(new int[]{i,j});
                    vis[i][j] = true;
                    enable++;
                }
            }
        }

        while(!q.isEmpty()) {
            int[] t= q.poll();
            int a = t[0], b = t[1];
            for(int i = 0; i < 4; i++) {
                int x = a + dx[i], y = b + dy[i];
                if(x>=0 && x<m && y>=0 && y<n && grid[x][y] == 1 && !vis[x][y]) {
                    enable++;
                    q.add(new int[]{x,y});
                    vis[x][y] = true;
                }
            }
        }
        int ans = total - enable;
        return ans;
    }
}
